package com.edu.internship.busi.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.edu.internship.busi.dto.LoginFormDTO;
import com.edu.internship.busi.entity.*;
import com.edu.internship.busi.service.*;
import com.edu.internship.config.redis.RedisUtil;
import com.edu.internship.glabal.constants.ResultCodeEnum;
import com.edu.internship.glabal.exception.BusinessException;

import com.google.common.collect.Sets;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * code is far away from bug with the animal protecting
 *
 * @author lishiquan
 * @description
 * @date 2022-07-29
 */
@RestController
@RequestMapping("api/auth")
@Slf4j
@Api(tags = {"登陆控制器"})
public class LoginController {

    @Resource
    private IDigitCaptchaService digitCaptchaService;
    @Resource
    private IUserService userService;
    @Resource
    private IUserRoleService userRoleService;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private IPermissionService permissionService;
    @Resource
    private RedisUtil redisUtil;
    private final String PREFIX = "TOKEN";

    @PostMapping("/login")
    @ApiOperation(value = "登陆", notes = "账号密码登陆")
    public List<User> login(@RequestBody LoginFormDTO form) {
        // TODO 自行实现登陆功能
        LambdaQueryWrapper<User> userQw = Wrappers.lambdaQuery();
        userQw.eq(User::getUsername, form.getUsername()).eq(User::getPassword,form.getPassword());
        List<User> list =  userService.list(userQw);
        boolean va = digitCaptchaService.validate(form.getCaptchaKey(),form.getCaptchaCode());
        if (list.size() != 0 & va) {
//            UserToken userToken = new UserToken();
//            userToken.setId(list.get(0).getId());
//            userToken.setUsername(form.getUsername());
//            log.info("h:{}",JwtUtils.getToken(userToken));
//           list.get(0).setJwt(JwtUtils.getToken(userToken));
            //登陆成功  设置token缓存

            list.get(0).setToken(StrUtil.uuid());
            redisUtil.set(list.get(0).getToken(),form.getUsername(),60*30 * 300);

            //从user_role表查角色id
            LambdaQueryWrapper<UserRole> urQw = Wrappers.lambdaQuery();
            urQw.eq(UserRole::getUId,list.get(0).getId());
            List<UserRole> urList = userRoleService.list(urQw);


            if (CollectionUtils.isEmpty(urList)) {
                throw new BusinessException(ResultCodeEnum.DATABASE_ERROR);
            }

            //从role_permission 表查权限id
            LambdaQueryWrapper<RolePermission> rpQw = Wrappers.lambdaQuery();
            List<String> roleIds = urList.stream().map(UserRole::getRId).collect(Collectors.toList());
            rpQw.in(RolePermission::getRId, roleIds);
            List<RolePermission> rpList = rolePermissionService.list(rpQw);
            if (CollectionUtils.isEmpty(rpList)) {
                throw new BusinessException(ResultCodeEnum.DATABASE_ERROR);
            }
            List<String> permissionIds = rpList.stream().map(RolePermission::getPId).distinct().collect(Collectors.toList());
            LambdaQueryWrapper<Permission> pQw = Wrappers.lambdaQuery();
            pQw.in(Permission::getId, permissionIds);

            List<Permission> permissions = permissionService.list(pQw);
            log.info("h:{}",permissions);
            Set<Permission> permissionSet = Sets.newHashSet(permissions);
            list.get(0).setPermission(permissionSet);
            return list;
        } else {
            return null;
        }
    }
}
